package database

import (
	"fmt"
	"wolongauth/config"
	"wolongauth/errhelp"
	"wolongauth/global"

	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func Run() {
	if config.GetConfig().Database == "mysql" {
		global.Logger.Info("正在打开mysql数据库", config.GetConfig().Mysql_Database, "...")
		dsn := fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.GetConfig().Mysql_User, config.GetConfig().Mysql_Pass, config.GetConfig().Mysql_Database)
		global.Logger.Debug(dsn)
		var err error
		UserDB, err = gorm.Open(mysql.Open(dsn))
		errhelp.ErrDoWithTagAndAbort(err, "open database")
	}
	if config.GetConfig().Database == "sqlite" {
		global.Logger.Info("正在打开sqlite数据库", config.GetConfig().Sqlite_Database, "...")
		var err error
		UserDB, err = gorm.Open(sqlite.Open(config.GetConfig().Sqlite_Database))
		errhelp.ErrDoWithTagAndAbort(err, "open database")
	}
	err := UserDB.AutoMigrate(&UserTableModel{})
	errhelp.ErrDoWithTagAndAbort(err, "AutoMigrate")
}
